from alipay import AliPay
from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response

from rest_framework.views import APIView
from django.conf import settings

from .models import Payment
from orders.models import OrderInfo


class AlipayView(APIView):
    def get(self, request, order_id):
        # 获得order对象
        try:
            order = OrderInfo.objects.get(order_id=order_id)
        except Exception as e:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # 生成公钥私钥
        app_private_key_path = settings.APP_PRIVATE_KEY_PATH
        alipay_public_key_path = settings.ALIPAY_PUBLIC_KEY_PATH

        # 创建AliPay对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
            app_private_key_path=app_private_key_path,

            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_path=alipay_public_key_path,

            sign_type="RSA2", # RSA 或者 RSA2
            debug=False  # 默认False
        )

        # 生成支付订单
        # 如果你是Python 2用户（考虑考虑升级到Python 3吧），请确保非ascii的字符串为utf8编码：
        # subject = u"测试订单".encode("utf8")

        # 如果你是 Python 3的用户，使用默认的字符串即可
        # subject = "测试订单"

        # 电脑网站支付，需要跳转到https://openapi.alipay.com/gateway.do? + order_string
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),  # 从用户对象取得总价格, Decimal 将int类型转成字符串
            subject="美多商城订单",
            return_url="http://www.meiduo.site:8080/pay_success.html",
            # notify_url="https://example.com/notify"  # 可选, 不填则使用默认notify url
        )

        # 返回支付页面
        alipay_url = settings.ALIPAY_URL + "?" + order_string
        return Response({"alipay_url": alipay_url})

class AlipayUpdeView(APIView):
    def put(self, request):
        # 获取参数
        data = request.query_params.dict()
        signature = data.pop('sign')

        # 效验参数
        app_private_key_path = settings.APP_PRIVATE_KEY_PATH
        alipay_public_key_path = settings.ALIPAY_PUBLIC_KEY_PATH
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,  # 默认回调url
             # 生成公钥私钥

            app_private_key_path=app_private_key_path,

            # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥,
            alipay_public_key_path=alipay_public_key_path,

            sign_type="RSA2", # RSA 或者 RSA2
            debug=False  # 默认False
        )
        success = alipay.verify(data, signature)

        if not success:
            return Response(status=status.HTTP_400_BAD_REQUEST)

        # 数据入库
        # 创建payment对象
        order_id = data.get("out_trade_no")
        trade_id = data.get("trade_no")
        Payment.objects.create(
            order_id=order_id,
            trade_id=trade_id
        )

        # 修改订单信息状态
        OrderInfo.objects.filter(order_id=order_id).update(status=OrderInfo.ORDER_STATUS_ENUM["UNSEND"])
        # 返回响应
        return Response({"trade_id": trade_id})




